<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
// 除了 E_NOTICE，报告其他所有错误
error_reporting(E_ERROR | E_PARSE);

use app\user\model\User;
use service\Str;
use think\Db;

// 应用公共文件
if (!function_exists('is_signin')) {
    /**
     * 判断管理员是否登录
     * @return mixed
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function is_signin()
    {
        $user = session('admin_auth');
        if (empty($user)) {

            return 0;
        } else {
            return session('admin_auth_sign') == data_auth_sign($user) ? $user['uid'] : 0;
        }
    }
}

if (!function_exists('data_auth_sign')) {
    /**
     * 数据签名认证
     * @param array $data 被认证的数据
     * @return string
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function data_auth_sign($data = [])
    {
        // 数据类型检测
        if (!is_array($data)) {
            $data = (array)$data;
        }

        // 排序
        ksort($data);
        // url编码并生成query字符串
        $code = http_build_query($data);
        // 生成签名
        $sign = sha1($code);
        return $sign;
    }
}
if (!function_exists('parse_attr')) {
    /**
     * 解析配置
     * @param string $value 配置值
     * @return array|string
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function parse_attr($value = '')
    {
        $array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));
        if (strpos($value, ':')) {
            $value = array();
            foreach ($array as $val) {
                list($k, $v) = explode(':', $val);
                $value[$k] = $v;
            }
        } else {
            $value = $array;
        }
        return $value;
    }
}

if (!function_exists('parse_sql')) {
    /**
     * 解析sql语句
     * @param string $content sql内容
     * @param int $limit 如果为1，则只返回一条sql语句，默认返回所有
     * @param array $prefix 替换表前缀
     * @return array|string 除去注释之后的sql语句数组或一条语句
     */
    function parse_sql($sql = '', $limit = 0, $prefix = [])
    {
        // 被替换的前缀
        $from = '';
        // 要替换的前缀
        $to = '';

        // 替换表前缀
        if (!empty($prefix)) {
            $to = current($prefix);
            $from = current(array_flip($prefix));
        }

        if ($sql != '') {
            // 纯sql内容
            $pure_sql = [];

            // 多行注释标记
            $comment = false;

            // 按行分割，兼容多个平台
            $sql = str_replace(["\r\n", "\r"], "\n", $sql);
            $sql = explode("\n", trim($sql));

            // 循环处理每一行
            foreach ($sql as $key => $line) {
                // 跳过空行
                if ($line == '') {
                    continue;
                }

                // 跳过以#或者--开头的单行注释
                if (preg_match("/^(#|--)/", $line)) {
                    continue;
                }

                // 跳过以/**/包裹起来的单行注释
                if (preg_match("/^\/\*(.*?)\*\//", $line)) {
                    continue;
                }

                // 多行注释开始
                if (substr($line, 0, 2) == '/*') {
                    $comment = true;
                    continue;
                }

                // 多行注释结束
                if (substr($line, -2) == '*/') {
                    $comment = false;
                    continue;
                }

                // 多行注释没有结束，继续跳过
                if ($comment) {
                    continue;
                }

                // 替换表前缀
                if ($from != '') {
                    $line = str_replace('`' . $from, '`' . $to, $line);
                }
                if ($line == 'BEGIN;' || $line == 'COMMIT;') {
                    continue;
                }
                // sql语句
                array_push($pure_sql, $line);
            }

            // 只返回一条语句
            if ($limit == 1) {
                return implode($pure_sql, "");
            }

            // 以数组形式返回sql语句
            $pure_sql = implode($pure_sql, "\n");
            $pure_sql = explode(";\n", $pure_sql);
            return $pure_sql;
        } else {
            return $limit == 1 ? '' : [];
        }
    }
}

if (!function_exists('get_client_ip')) {
    /**
     * 获取客户端IP地址
     * @param int $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
     * @param bool $adv 是否进行高级模式获取（有可能被伪装）
     * @return mixed
     */
    function get_client_ip($type = 0, $adv = false)
    {
        $type = $type ? 1 : 0;
        static $ip = NULL;
        if ($ip !== NULL) return $ip[$type];
        if ($adv) {
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                $pos = array_search('unknown', $arr);
                if (false !== $pos) unset($arr[$pos]);
                $ip = trim($arr[0]);
            } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $ip = $_SERVER['HTTP_CLIENT_IP'];
            } elseif (isset($_SERVER['REMOTE_ADDR'])) {
                $ip = $_SERVER['REMOTE_ADDR'];
            }
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u", ip2long($ip));
        $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }
}
if (!function_exists('get_file_url')) {
    /**
     * 获取附件路径
     * @param int $id 附件id
     * @return string
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function get_file_url($id, $type = 0)
    {
        if (!is_numeric($id)) {
            return $id;
        }
        $path = model('admin/upload')->getFilePath($id);
        if (empty($path)) {
            if ($type == 0) {
                return config('web_site_domain') . '/static/admin/images/none.png';
            }
            return "";
        }
        return $path;
    }
}
if (!function_exists('get_thumb_file_url')) {
    /**
     * 获取缩略图路径
     * @param int $id 附件id
     * @return string
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function get_thumb_file_url($id, $type = 0)
    {
        if (!is_numeric($id)) {
            return $id;
        }
        $path = model('admin/upload')->getThumbPath($id);
        if (empty($path)) {
            if ($type == 0) {
                return config('web_site_domain') . '/static/admin/images/none.png';
            }
            return "";
        }
        return $path;
    }
}


if (!function_exists('get_files_url')) {
    /**
     * 批量获取附件路径
     * @param array $ids 附件id
     * @return array
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function get_files_url($ids = [])
    {
        if (!is_array($ids)) {
            $ids = explode(',', $ids);
        }
        $paths = model('admin/upload')->getFilePath($ids);
        return !$paths ? [] : array_filter($paths);
    }
}

if (!function_exists('get_thumb')) {
    /**
     * 获取缩略图路径
     * @param int $id 附件id
     * @return string
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function get_thumb($id)
    {
        if (!is_numeric($id)) {
            return $id;
        }
        $path = model('admin/upload')->getThumbPath($id);
        // $path打印是0 
        if (empty($path)) {
            return config('web_site_domain') . '/static/admin/images/none.png';
        }
        return $path;
    }
}

if (!function_exists('hook')) {
    /**
     * 监听钩子
     * @param string $name 钩子名称
     * @param mixed $params 传入参数
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function hook($name = '', $params = null)
    {
        \Hook::listen($name, $params);
    }
}

if (!function_exists('p')) {
    /**
     * 打印调试信息
     * @param 不限类型 var 变量
     * @return string
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function p($var)
    {
        if (is_bool($var)) {
            var_dump($var);
        } else if (is_null($var)) {
            var_dump(NULL);
        } else {
            echo "<pre style='position:relative;z-index:1000;padding:10px;border-radius:5px;background:#F5F5F5;border:1px solid #aaa;font-size:14px;line-height:18px;opacity:0.9;'>" . print_r($var, true) . "</pre>";
        }
    }
}

if (!function_exists('get_location')) {
    /**
     * 获取当前位置
     * @param string $id 节点id，如果没有指定，则取当前节点id
     * @param bool $del_last_url 是否删除最后一个节点的url地址
     * @param bool $check 检查节点是否存在，不存在则抛出错误
     * @return mixed
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function get_location($id = '', $del_last_url = false, $check = true)
    {
        $location = model('admin/menu')->getLocation($id, $del_last_url, $check);
        return $location;
    }
}

if (!function_exists('format_linkage')) {
    /**
     * 格式化联动数据
     * @param array $data 数据
     * @return array
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function format_linkage($data = [])
    {
        $list = [];
        foreach ($data as $key => $value) {
            $list[] = [
                'key' => $key,
                'value' => $value
            ];
        }
        return $list;
    }
}

if (!function_exists('format_bytes')) {
    /**
     * 格式化字节大小
     * @param number $size 字节数
     * @param string $delimiter 数字和单位分隔符
     * @return string            格式化后的带单位的大小
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    function format_bytes($size, $delimiter = '')
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
        return round($size, 2) . $delimiter . $units[$i];
    }
}

if (!function_exists('action_log')) {
    /**
     * 记录行为日志，并执行该行为的规则
     * @param null $action 行为标识
     * @param null $model 触发行为的模型名
     * @param string $record_id 触发行为的记录id
     * @param null $user_id 执行行为的用户id
     * @param string $details 详情
     * @return bool|string
     */
    function action_log($action = null, $model = null, $record_id = '', $user_id = null, $details = '')
    {
        // 判断是否开启系统日志功能
        if (config('system_log')) {
            // 参数检查
            if (empty($action) || empty($model)) {
                return '参数不能为空';
            }
            if (empty($user_id)) {
                $user_id = is_signin();
            }
            if (strpos($action, '.')) {
                list($module, $action) = explode('.', $action);
            } else {
                $module = request()->module();
            }

            // 查询行为,判断是否执行
            $action_info = model('admin/action')->where('module', $module)->getByName($action);

            if ($action_info['status'] != 1) {
                return '该行为被禁用或删除';
            }

            // 插入行为日志
            $data = [
                'action_id' => $action_info['id'],
                'user_id' => $user_id,
                'action_ip' => get_client_ip(1),
                'model' => $model,
                'record_id' => $record_id,
                'create_time' => request()->time()
            ];

            // 解析日志规则,生成日志备注
            if (!empty($action_info['log'])) {
                if (preg_match_all('/\[(\S+?)\]/', $action_info['log'], $match)) {
                    $log = [
                        'user' => $user_id,
                        'record' => $record_id,
                        'model' => $model,
                        'time' => request()->time(),
                        'data' => ['user' => $user_id, 'model' => $model, 'record' => $record_id, 'time' => request()->time()],
                        'details' => $details
                    ];

                    $replace = [];
                    foreach ($match[1] as $value) {
                        $param = explode('|', $value);
                        if (isset($param[1])) {
                            $replace[] = call_user_func($param[1], $log[$param[0]]);
                        } else {
                            $replace[] = $log[$param[0]];
                        }
                    }

                    $data['remark'] = str_replace($match[0], $replace, $action_info['log']);
                } else {
                    $data['remark'] = $action_info['log'];
                }
            } else {
                // 未定义日志规则，记录操作url
                $data['remark'] = '操作url：' . $_SERVER['REQUEST_URI'];
            }

            // 保存日志
            model('admin/log')->insert($data);

            if (!empty($action_info['rule'])) {
                // 解析行为
                $rules = parse_action($action, $user_id);
                // 执行行为
                $res = execute_action($rules, $action_info['id'], $user_id);
                if (!$res) {
                    return '执行行为失败';
                }
            }
        }

        return true;
    }
}

if (!function_exists('parse_action')) {
    /**
     * 解析行为规则
     * 规则定义  table:$table|field:$field|condition:$condition|rule:$rule[|cycle:$cycle|max:$max][;......]
     * 规则字段解释：table->要操作的数据表，不需要加表前缀；
     *            field->要操作的字段；
     *            condition->操作的条件，目前支持字符串，默认变量{$self}为执行行为的用户
     *            rule->对字段进行的具体操作，目前支持四则混合运算，如：1+score*2/2-3
     *            cycle->执行周期，单位（小时），表示$cycle小时内最多执行$max次
     *            max->单个周期内的最大执行次数（$cycle和$max必须同时定义，否则无效）
     * 单个行为后可加 ； 连接其他规则
     * @param string $action 行为id或者name
     * @param int $self 替换规则里的变量为执行用户的id
     * @return boolean|array: false解析出错 ， 成功返回规则数组
     */
    function parse_action($action = null, $self)
    {
        if (empty($action)) {
            return false;
        }

        // 参数支持id或者name
        if (is_numeric($action)) {
            $map = ['id' => $action];
        } else {
            $map = ['name' => $action];
        }

        // 查询行为信息
        $info = model('admin/action')->where($map)->find();
        if (!$info || $info['status'] != 1) {
            return false;
        }

        // 解析规则:table:$table|field:$field|condition:$condition|rule:$rule[|cycle:$cycle|max:$max][;......]
        $rule = $info['rule'];
        $rule = str_replace('{$self}', $self, $rule);
        $rules = explode(';', $rule);
        $return = [];
        foreach ($rules as $key => &$rule) {
            $rule = explode('|', $rule);
            foreach ($rule as $k => $fields) {
                $field = empty($fields) ? array() : explode(':', $fields);
                if (!empty($field)) {
                    $return[$key][$field[0]] = $field[1];
                }
            }
            // cycle(检查周期)和max(周期内最大执行次数)必须同时存在，否则去掉这两个条件
            if (!isset($return[$key]['cycle']) || !isset($return[$key]['max'])) {
                unset($return[$key]['cycle'], $return[$key]['max']);
            }
        }

        return $return;
    }
}

if (!function_exists('execute_action')) {
    /**
     * 执行行为
     * @param array|bool $rules 解析后的规则数组
     * @param int $action_id 行为id
     * @param array $user_id 执行的用户id
     * @return boolean false 失败 ， true 成功
     */
    function execute_action($rules = false, $action_id = null, $user_id = null)
    {
        if (!$rules || empty($action_id) || empty($user_id)) {
            return false;
        }

        $return = true;
        foreach ($rules as $rule) {
            // 检查执行周期
            $map = ['action_id' => $action_id, 'user_id' => $user_id];
            $map['create_time'] = ['gt', request()->time() - intval($rule['cycle']) * 3600];
            $exec_count = model('admin/log')->where($map)->count();
            if ($exec_count > $rule['max']) {
                continue;
            }

            // 执行数据库操作
            $field = $rule['field'];
            $res = Db::name($rule['table'])->where($rule['condition'])->setField($field, array('exp', $rule['rule']));

            if (!$res) {
                $return = false;
            }
        }
        return $return;
    }
}

if (!function_exists('role_auth')) {
    /**
     * 读取当前用户权限
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function role_auth()
    {
        session('role_menu_auth', model('admin/role')->roleAuth());
    }
}

if (!function_exists('module_config')) {
    /**
     * 显示当前模块的参数配置页面，或获取参数值，或设置参数值
     * @param string $name
     * @param string $value
     * @return mixed
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function module_config($name = '', $value = '')
    {
        if ($name === '') {
            // 显示模块配置页面
            return action('admin/admin/moduleConfig');
        } elseif ($value === '') {
            // 获取模块配置
            if (strpos($name, '.')) {
                list($name, $item) = explode('.', $name);
                return model('admin/module')->getConfig($name, $item);
            } else {
                return model('admin/module')->getConfig($name);
            }
        } else {
            // 设置值
            return model('admin/module')->setConfig($name, $value);
        }
    }
}

if (!function_exists('addons_menage')) {
    /**
     * 显示插件的管理页面
     * @param string $name 插件名
     * @return mixed
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function addons_menage($name = '')
    {
        return action('admin/addons/manage', ['name' => $name]);
    }
}

if (!function_exists('addons_config')) {
    /**
     * 获取或设置某个插件配置参数
     * @param string $name 插件名.配置名
     * @param string $value 设置值
     * @return mixed
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function addons_config($name = '', $value = '')
    {
        if ($value === '') {
            // 获取插件配置
            if (strpos($name, '.')) {
                list($name, $item) = explode('.', $name);
                return model('admin/addons')->getConfig($name, $item);
            } else {
                return model('admin/addons')->getConfig($name);
            }
        } else {
            return model('admin/addons')->setConfig($name, $value);
        }
    }
}

if (!function_exists('get_addons_class')) {
    /**
     * 获取插件类名
     * @param string $name 插件名
     * @return string
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function get_addons_class($name)
    {
        return "addons\\{$name}\\{$name}";
    }
}

if (!function_exists('addons_action_exists')) {
    /**
     * 检查插件控制器是否存在某操作
     * @param string $name 插件名
     * @param string $controller 控制器
     * @param string $action 动作
     * @return bool
     * @author 似水星辰 [2630481389@qq.com]
     */
    function addons_action_exists($name = '', $controller = '', $action = '')
    {
        if (strpos($name, '/')) {
            list($name, $controller, $action) = explode('/', $name);
        }
        return method_exists("addons\\{$name}\\controller\\{$controller}", $action);
    }
}

if (!function_exists('addons_model_exists')) {
    /**
     * 检查插件模型是否存在
     * @param string $name 插件名
     * @return bool
     * @author 似水星辰 [2630481389@qq.com]
     */
    function addons_model_exists($name = '')
    {
        return class_exists("addons\\{$name}\\model\\{$name}");
    }
}

if (!function_exists('addons_validate_exists')) {
    /**
     * 检查插件验证器是否存在
     * @param string $name 插件名
     * @return bool
     * @author 似水星辰 [2630481389@qq.com]
     */
    function addons_validate_exists($name = '')
    {
        return class_exists("addons\\{$name}\\validate\\{$name}");
    }
}

if (!function_exists('get_addons_model')) {
    /**
     * 获取插件模型实例
     * @param string $name 插件名
     * @return object
     * @author 似水星辰 [2630481389@qq.com]
     */
    function get_addons_model($name)
    {
        $class = "addons\\{$name}\\model\\{$name}";
        return new $class;
    }
}

if (!function_exists('get_model_name')) {
    /**
     * 获取内容模型名称
     * @param string $id 内容模型id
     * @return string
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function get_model_name($id = '')
    {
        $model_list = model('admin/model')->getList();
        return isset($model_list[$id]) ? $model_list[$id]['name'] : '';
    }
}

if (!function_exists('get_model_title')) {
    /**
     * 获取内容模型标题
     * @param string $id 内容模型标题
     * @return string
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function get_model_title($id = '')
    {
        $model_list = model('admin/model')->getList();
        return isset($model_list[$id]) ? $model_list[$id]['title'] : '';
    }
}

if (!function_exists('get_model_type')) {
    /**
     * 获取内容模型类别：0-系统，1-普通，2-独立
     * @param int $id 模型id
     * @return string
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function get_model_type($id = 0)
    {
        $model_list = model('admin/model')->getList();
        return isset($model_list[$id]) ? $model_list[$id]['type'] : '';
    }
}

if (!function_exists('get_model_table')) {
    /**
     * 获取内容模型附加表名
     * @param int $id 模型id
     * @return string
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function get_model_table($id = 0)
    {
        $model_list = model('admin/model')->getList();
        return isset($model_list[$id]) ? $model_list[$id]['table'] : '';
    }
}

if (!function_exists('is_default_field')) {
    /**
     * 检查是否为系统默认字段
     * @param string $field 字段名称
     * @return bool
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function is_default_field($field = '')
    {
        $system_fields = cache('admin_system_fields');
        if (!$system_fields) {
            $system_fields = Db::name('admin_model_field')->where('model', 0)->column('name');
            cache('admin_system_fields', $system_fields);
        }
        return in_array($field, $system_fields, true);
    }
}

if (!function_exists('table_exist')) {
    /**
     * 检查附加表是否存在
     * @param string $table_name 附加表名
     * @return string
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function table_exist($table_name = '')
    {
        $table_name = config('database.prefix') . $table_name;
        return true == Db::query("SHOW TABLES LIKE '{$table_name}'");
    }
}
if (!function_exists('implode_attr')) {
    /**
     * 组合配置
     * @param array $array 配置值
     * @return string
     */
    function implode_attr($array = [])
    {
        $result = [];
        foreach ($array as $key => $value) {
            $result[] = $key . ':' . $value;
        }
        return empty($result) ? '' : implode(PHP_EOL, $result);
    }
}

if (!function_exists('parse_array')) {
    /**
     * 将一维数组解析成键值相同的数组
     * @param array $arr 一维数组
     * @return array
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function parse_array($arr)
    {
        $result = [];
        foreach ($arr as $item) {
            $result[$item] = $item;
        }
        return $result;
    }
}

if (!function_exists('parse_name')) {
    /**
     * 字符串命名风格转换
     * type 0 将Java风格转换为C的风格 1 将C风格转换为Java的风格
     * @param string $name 字符串
     * @param integer $type 转换类型
     * @return string
     */
    function parse_name($name, $type = 0)
    {
        if ($type) {
            return ucfirst(preg_replace_callback('/_([a-zA-Z])/', function ($match) {
                return strtoupper($match[1]);
            }, $name));
        } else {
            return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_"));
        }
    }
}
if (!function_exists('parse_config')) {
    /**
     * 解析配置，返回配置值
     * @param array $configs 配置
     * @return array
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function parse_config($configs = [])
    {
        $type = [
            'hidden' => 2,
            'image' => 4,
            'images' => 4,
            'number' => 4,
            'tags' => 4,
            'text' => 4,
            'array' => 4,
            'textarea' => 4,
            'wangeditor' => 4,
            'radio' => 5,
            'select' => 5,
            'linkage' => 5,
            'checkbox' => 5,
            'linkages' => 6
        ];
        $result = [];
        foreach ($configs as $item) {
            $result[$item[1]] = isset($item[$type[$item[0]]]) ? $item[$type[$item[0]]] : '';
        }
        return $result;
    }
}

if (!function_exists('addons_parse_config')) {
    /**
     * 解析配置，返回配置值
     * @param array $configs 配置
     * @return array
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function addons_parse_config($configs = [])
    {
        $type = [
            'hidden' => 2,
            'image' => 4,
            'images' => 4,
            'number' => 4,
            'tags' => 4,
            'text' => 4,
            'array' => 4,
            'textarea' => 4,
            'wangeditor' => 4,
            'radio' => 5,
            'select' => 5,
            'linkage' => 5,
            'checkbox' => 5,
            'linkages' => 6
        ];
        $result = [];
        foreach ($configs as $item) {
            $result[$item['name']] = isset($item['value']) ? $item['value'] : '';
        }
        return $result;
    }
}

if (!function_exists('addons_action')) {
    /**
     * 执行插件动作
     * 也可以用这种方式调用：addons_action('插件名/控制器/动作', [参数1,参数2...])
     * @param string $name 插件名
     * @param string $controller 控制器
     * @param string $action 动作
     * @param mixed $params 参数
     * @return mixed
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function addons_action($name = '', $controller = '', $action = '', $params = [])
    {
        if (strpos($name, '/')) {
            $params = is_array($controller) ? $controller : (array)$controller;
            list($name, $controller, $action) = explode('/', $name);
        }
        if (!is_array($params)) {
            $params = (array)$params;
        }
        $class = "addons\\{$name}\\controller\\{$controller}";
        $obj = new $class;
        return call_user_func_array([$obj, $action], $params);
    }
}
if (!function_exists('model_action')) {
    /**
     * 执行模块动作
     * 也可以用这种方式调用：model_action('模块名/控制器/动作', [参数1,参数2...])
     * @param string $name 模块名
     * @param string $controller 控制器
     * @param string $action 动作
     * @param mixed $params 参数
     * @return mixed
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function model_action($name = '', $controller = '', $action = '', $params = [])
    {
        if (strpos($name, '/')) {
            $params = is_array($controller) ? $controller : (array)$controller;
            list($name, $controller, $action) = explode('/', $name);
        }
        if (!is_array($params)) {
            $params = (array)$params;
        }
        $class = "{$name}\\api\\controller\\v1\\{$controller}";
        $obj = new $class;
        return call_user_func_array([$obj, $action], $params);
    }
}
if (!function_exists('get_adminname')) {
    /**
     * 根据后台用户ID获取用户昵称
     * @param integer $uid 用户ID
     * @return string       用户昵称
     */
    function get_adminname($uid = 0)
    {
        static $list;
        if (!($uid && is_numeric($uid))) { //获取当前登录用户名
            return session('admin_auth.nickname');
        }

        /* 获取缓存数据 */
        if (empty($list)) {
            $list = cache('sys_admin_nickname_list');
        }

        /* 查找用户信息 */
        $key = "u{$uid}";
        if (isset($list[$key])) { //已缓存，直接使用
            $name = $list[$key];
        } else { //调用接口获取用户信息
            $info = Db::name('admin')->field('nickname')->find($uid);
            if ($info !== false && $info['nickname']) {
                $nickname = $info['nickname'];
                $name = $list[$key] = $nickname;
                /* 缓存用户 */
                $count = count($list);
                $max = 10;
                while ($count-- > $max) {
                    array_shift($list);
                }
                cache('sys_admin_nickname_list', $list);
            } else {
                $name = '';
            }
        }
        return $name;
    }
}

if (!function_exists('get_nickname')) {
    /**
     * 获取会员昵称
     * @param $id 会员id
     * @return void
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function get_nickname($id)
    {
        return \think\Db::name('user')->where('id', $id)->value('user_nickname');
    }
}

if (!function_exists('get_user_info')) {
    /**
     * 获取会员信息
     * @param $id 会员ID
     * @param null $key 指定字段
     * @return array|PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function get_user_info($id, $key = null)
    {
        $info = \think\Db::name('user')->where('id', $id)->find();
        if (empty($key)) {
            return $info;
        }
        return isset($info[$key]) ? $info[$key] : '';
    }
}


if (!function_exists('set_config_value')) {
    /**
     * 设置配置的值，并返回配置好的数组
     * @param array $configs 配置
     * @param array $values 配置值
     * @return array
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function set_config_value($configs = [], $values = [])
    {
        $type = [
            'hidden' => 2,
            'date' => 4,
            'ckeditor' => 4,
            'daterange' => 4,
            'datetime' => 4,
            'editormd' => 4,
            'file' => 4,
            'colorpicker' => 4,
            'files' => 4,
            'icon' => 4,
            'image' => 4,
            'images' => 4,
            'jcrop' => 4,
            'range' => 4,
            'number' => 4,
            'password' => 4,
            'sort' => 4,
            'static' => 4,
            'summernote' => 4,
            'switch' => 4,
            'tags' => 4,
            'text' => 4,
            'array' => 4,
            'textarea' => 4,
            'time' => 4,
            'ueditor' => 4,
            'wangeditor' => 4,
            'radio' => 5,
            'bmap' => 5,
            'masked' => 5,
            'select' => 5,
            'linkage' => 5,
            'checkbox' => 5,
            'linkages' => 6
        ];

        foreach ($configs as &$item) {
            if (strpos($item[0], ':')) {
                list($config_type, $layout) = explode(':', $item[0]);
            } else {
                $config_type = $item[0];
            }

            // 判断是否为分组
            if ($config_type == 'group') {
                foreach ($item[1] as &$option) {
                    foreach ($option as $group => &$val) {
                        $val[$type[$val[0]]] = isset($values[$val[1]]) ? $values[$val[1]] : '';
                    }
                }
            } else {
                $item[$type[$config_type]] = isset($values[$item[1]]) ? $values[$item[1]] : '';
            }
        }
        return $configs;
    }
}

if (!function_exists('get_file_name')) {
    /**
     * 根据附件id获取文件名
     * @param string $id 附件id
     * @return string
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function get_file_name($id = '')
    {
        $name = model('admin/upload')->getFileName($id);
        if (!$name) {
            return '没有找到文件';
        }
        return $name;
    }
}

if (!function_exists('getIntervalTime')) {
    /**
     * 计算同比上个档次时间
     * @param  [type]  $time         [description]
     * @param integer $intervalType 1：上周,2:本月,3:上一个月,4:本季度,5:上一个季度,6:本年,7:去年,8:昨天
     * @return [type]                [description]
     */
    function getIntervalTime($time, $intervalType = 1)
    {
        switch ($intervalType) {
            case 2:
                // 本月
                $stime = date('Y-m-d', strtotime(date('Y-m', $time)));
                $etime = date('Y-m-d', $time) . " 23:59:59";
                break;
            case 3:
                // 同比本月（上个月）
                $stime = date('Y-m-d', strtotime('-1 month', strtotime(date('Y-m', $time))));
                // 上月有28天 查的是31号的数据
                $yday = date('t', strtotime($stime));; // 上个月的天数
                $byday = date('t', $time); // 本月的天数
                $bday = date("d", $time); //本月查的天数
                if ($yday < $bday) {
                    $etime = date("Y-m", strtotime($stime)) . "-" . $yday . " 23:59:59";
                } else if ($byday == $bday) {
                    $etime = date('Y-m', strtotime($stime)) . "-" . $yday . " 23:59:59";
                } else {
                    $etime = date('Y-m-d', strtotime('-1 month', $time)) . " 23:59:59";
                }
                break;
            case 4:
                $season = ceil((date('n', $time)) / 3);
                $stime = date('Y-m-d', mktime(0, 0, 0, $season * 3 - 3 + 1, 1, date('Y', $time)));
                $etime = date("Y-m-d", $time) . " 23:59:59";
                break;
            case 5:
                $season = ceil((date('n', $time)) / 3) - 1;//上季度是第几季度
                $stime = date('Y-m-d', mktime(0, 0, 0, $season * 3 - 3 + 1, 1, date('Y', $time)));
                $xetime = date('Y-m-d', mktime(23, 59, 59, $season * 3, date('t', mktime(0, 0, 0, $season * 3, 1, date("Y", $time))), date('Y', $time))) . "\n";
                $year = date("z", mktime(23, 59, 59, 12, 31, date("Y", $time))) + 1;
                $dtime = date("m-d", $time);
                $petime = strtotime($xetime);
                if ($year == 366 && $dtime == "02-29") {
                    $etime = date("Y", $petime) . "-11-30" . " 23:59:59";
                } else if ($year == 366 && ($dtime == "05-31" || $dtime == "05-30")) {
                    $etime = date("Y", $petime) . "-2-29" . " 23:59:59";
                } else if ($year == 365 && $dtime == "02-28") {
                    $etime = date("Y", $petime) . "-11-30" . " 23:59:59";
                } else if ($year == 365 && ($dtime == "05-31" || $dtime == "05-30" || $dtime == "05-29")) {
                    $etime = date("Y", $petime) . "-2-28" . " 23:59:59";
                } else {
                    $etime = date("Y-m-d", strtotime("-3 month", $time)) . " 23:59:59";
                }
                break;
            case 6:
                $stime = date("Y", $time) . "-01-01";
                $etime = date("Y-m-d", $time) . " 23:59:59";
                break;
            case 7:
                $stime = date("Y", strtotime("-1 year", $time)) . "-01-01";
                $jy = date("Y", $time);
                $jyear = date("z", mktime(23, 59, 59, 12, 31, $jy)) + 1;// 今年天数
                $syin = strtotime("-1 year", $time); //上一年 int
                $qn = date("Y", $syin);
                $qyear = date("z", mktime(23, 59, 59, 12, 31, $qn)) + 1; // 去年的天数
                $tday = date("m-d", $time);
                if (($jyear < $qyear) && $tday == '02-28') {
                    $etime = date("Y", $syin) . "-02-29" . " 23:59:59";
                } else if (($jyear > $qyear) && $tday == '02-29') {
                    $etime = date("Y", $syin) . "-02-28" . " 23:59:59";
                } else {
                    $etime = date("Y-m-d", $syin) . " 23:59:59";
                }
                break;
            case 8:
                $stime = date("Y-m-d", strtotime("-1 day"));
                $etime = date("Y-m-d", strtotime("-1 day")) . " 23:59:59";
                break;
            default:
                // 同比上周
                if (date('w', $time) == 1) { // 判断今天是一周的第几天
                    $stime = date('Y-m-d', strtotime('-7 day', $time));
                } else {
                    $stime = date('Y-m-d', strtotime('-2 monday', $time));
                }
                $etime = date('Y-m-d', strtotime('-7 day', $time)) . " 23:59:59";
        }// end of switch
        return array('startTime' => strtotime($stime), 'endTime' => strtotime($etime));
    }

}

if (!function_exists('format_time')) {
    /**
     * 时间戳格式化
     * @param string $time 时间戳
     * @param string $format 输出格式
     * @return false|string
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function format_time($time = '', $format = 'Y-m-d H:i:s')
    {
        return !$time ? '' : date($format, intval($time));
    }
}

if (!function_exists('get_order_sn')) {

    /**
     * 生成订单号
     * @param string $type S为商城订单，C为充值订单
     * @return void
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @since 2019-04-03 17:00
     */
    function get_order_sn($type = 'S')
    {
        //生成随机3位数字
        $rand = service\Str::randString(3, 1);
        //获取当前毫秒时间
        $msec = substr(get_msectime(), 10);
        //和当前时间组合得到订单号
        $orderSn = $type . date('YmdHis', time()) . $msec . $rand;

        return $orderSn;
    }
}

if (!function_exists('get_msectime')) {

    /**
     * 返回当前的毫秒时间戳
     * @return float
     * @since 2019/4/3 17:28
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function get_msectime()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }
}

if (!function_exists('timeToHIS')) {
    /**
     * 格式化时间为h:i:s
     * @param int $cha 时间戳之差的绝对值
     * @return string
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function timeToHIS($cha, $ext = ":/:/")
    {
        $ii = floor($cha / 60); //得到多少分
        $h = floor($ii / 60); //得到多少时
        /* 秒 */
        $s = $cha % 60;
        /* 分*/
        $i = floor($ii % 60);

        //一小时内 不带小时
        list($a, $b, $c) = explode('/', $ext);
        if ($ii < 60) {
            return sprintf('%02d', $i) . $b . sprintf('%02d', $s) . $c;
        } else {
            return $h . $a . sprintf('%02d', $i) . $b . sprintf('%02d', $s) . $c;
        }
    }
}
if (!function_exists('getMobileType')) {
    /**
     * 判断手机类型 安卓还是IOS
     * @return string
     * @since 2019/4/17 18:20
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function getMobileType()
    {
        $ua = $_SERVER['HTTP_USER_AGENT'] ? $_SERVER['HTTP_USER_AGENT'] : '';
        if (strpos($ua, 'iPhone') || strpos($ua, 'iPad')) {
            return 'ios';
        }
        if (strpos($ua, 'Android') || strpos($ua, 'android')) {
            return 'android';
        }
        return 'other';
    }
}

if (!function_exists('curl_post')) {

    /**
     * CURL POST
     * @param $url 请求地址
     * @param $data 请求数据
     * @return void
     * @since 2019/4/17 18:20
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function curl_post($url, $data)
    {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $output = curl_exec($ch);
        curl_close($ch);

        return $output;
    }
}
if (!function_exists('friend_date')) {

    /**
     * 友好时间
     * @param $time
     * author 风轻云淡
     * @return bool|false|string
     */
    function friend_date($time)
    {
        if (!$time)
            return false;
        $fdate = '';
        $d = time() - intval($time);
        $ld = $time - mktime(0, 0, 0, 0, 0, date('Y')); //得出年
        $md = $time - mktime(0, 0, 0, date('m'), 0, date('Y')); //得出月
        $byd = $time - mktime(0, 0, 0, date('m'), date('d') - 2, date('Y')); //前天
        $yd = $time - mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')); //昨天
        $dd = $time - mktime(0, 0, 0, date('m'), date('d'), date('Y')); //今天
        $td = $time - mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')); //明天
        $atd = $time - mktime(0, 0, 0, date('m'), date('d') + 2, date('Y')); //后天
        if ($d == 0) {
            $fdate = '刚刚';
        } else {
            switch ($d) {
                case $d < $atd:
                    $fdate = date('Y-m-d', $time);
                    break;
                case $d < $td:
                    $fdate = '后天' . date('H:i', $time);
                    break;
                case $d < 0:
                    $fdate = '明天' . date('H:i', $time);
                    break;
                case $d < 60:
                    $fdate = $d . '秒前';
                    break;
                case $d < 3600:
                    $fdate = floor($d / 60) . '分钟前';
                    break;
                case $d < $dd:
                    $fdate = floor($d / 3600) . '小时前';
                    break;
                case $d < $yd:
                    $fdate = '昨天' . date('H:i', $time);
                    break;
                case $d < $byd:
                    $fdate = '前天' . date('H:i', $time);
                    break;
                case $d < $md:
                    $fdate = date('m/d日 H:i', $time);
                    break;
                case $d < $ld:
                    $fdate = date('m/d', $time);
                    break;
                default:
                    $fdate = date('Y-m-d', $time);
                    break;
            }
        }
        return $fdate;
    }
}

if (!function_exists('str2sub')) {
    /**
     * 字符串截取
     * @param $str
     * @param int $length
     * @param string $append
     * @return bool|string
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function str2sub($str, $length = 0, $append = '...')
    {
        $str = trim($str);
        $strlength = strlen($str);

        if ($length == 0 || $length >= $strlength) {
            return $str;
        } elseif ($length < 0) {
            $length = $strlength + $length;
            if ($length < 0) {
                $length = $strlength;
            }
        }

        if (function_exists('mb_substr')) {
            $newstr = mb_substr($str, 0, $length, 'utf-8');
        } elseif (function_exists('iconv_substr')) {
            $newstr = iconv_substr($str, 0, $length, 'utf-8');
        } else {
            //$newstr = trim_right(substr($str, 0, $length));
            $newstr = substr($str, 0, $length);
        }

        if ($append && $str != $newstr) {
            $newstr .= $append;
        }

        return $newstr;
    }
}

/**
 * 创建快速多级联动Token
 * @param string $table 表名
 * @param string $option
 * @param string $key
 * @return bool|string
 * @author 似水星辰 [2630481389@qq.com]
 */
function createLinkagesToken($table = '', $option = '', $key = '')
{
    $table_token = substr(sha1($table . '-' . $option . '-' . $key . '-' . session('user_auth.last_login_ip') . '-' . UID . '-' . session('user_auth.last_login_time')), 0, 8);
    session($table_token, ['table' => $table, 'option' => $option, 'key' => $key]);
    return $table_token;
}

if (!function_exists('get_level_data')) {
    /**
     * 获取联动数据
     * @param string $table 表名
     * @param int $pid 父级ID
     * @param string $pid_field 父级ID的字段名
     * @return array|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author 似水星辰 [2630481389@qq.com]
     */
    function get_level_data($table = '', $pid = 0, $pid_field = 'pid')
    {
        if ($table == '') {
            return '';
        }

        $data_list = Db::name($table)->where($pid_field, $pid)->select();

        if ($data_list) {
            return $data_list;
        } else {
            return '';
        }
    }
}

if (!function_exists('get_level_pid')) {
    /**
     * 获取联动等级和父级id
     * @param string $table 表名
     * @param int $id 主键值
     * @param string $id_field 主键名
     * @param string $pid_field pid字段名
     * @return mixed
     * @author 似水星辰 [2630481389@qq.com]
     */
    function get_level_pid($table = '', $id = 1, $id_field = 'id', $pid_field = 'pid')
    {
        return Db::name($table)->where($id_field, $id)->value($pid_field);
    }
}

if (!function_exists('get_level_key_data')) {
    /**
     * 反向获取联动数据
     * @param string $table 表名
     * @param string $id 主键值
     * @param string $id_field 主键名
     * @param string $name_field name字段名
     * @param string $pid_field pid字段名
     * @param int $level 级别
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author 似水星辰 [2630481389@qq.com]
     */
    function get_level_key_data($table = '', $id = '', $id_field = 'id', $name_field = 'name', $pid_field = 'pid', $level = 1)
    {
        $result = [];
        $level_pid = get_level_pid($table, $id, $id_field, $pid_field);
        $level_key[$level] = $level_pid;
        $level_data[$level] = get_level_data($table, $level_pid, $pid_field);

        if ($level_pid != 0) {
            $data = get_level_key_data($table, $level_pid, $id_field, $name_field, $pid_field, $level + 1);
            $level_key = $level_key + $data['key'];
            $level_data = $level_data + $data['data'];
        }
        $result['key'] = $level_key;
        $result['data'] = $level_data;

        return $result;
    }
}

if (!function_exists('clear_js')) {
    /**
     * 过滤js内容
     * @param string $str 要过滤的字符串
     * @return mixed|string
     * @author 似水星辰 [2630481389@qq.com]
     */
    function clear_js($str = '')
    {
        $search = "/<script[^>]*?>.*?<\/script>/si";
        $str = preg_replace($search, '', $str);
        return $str;
    }
}

if (!function_exists('get_sex')) {
    /**
     * 获取性别
     * @return void
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function get_sex($sex)
    {
        $data = ['女', '男'];
        return $data[$sex];
    }
}
if (!function_exists('get_age')) {
    /**
     * 准备工作完毕 开始计算年龄函数
     * @param $birthday 出生时间 uninx时间戳
     * @param $time 当前时间
     * @return false|string
     */
    function get_age($birthday)
    {
        //格式化出生时间年月日
        $byear = date('Y', $birthday);
        $bmonth = date('m', $birthday);
        $bday = date('d', $birthday);

        //格式化当前时间年月日
        $tyear = date('Y');
        $tmonth = date('m');
        $tday = date('d');

        //开始计算年龄
        $age = $tyear - $byear;
        if ($bmonth > $tmonth || $bmonth == $tmonth && $bday > $tday) {
            $age--;
        }
        return $age;
    }
}


if (!function_exists('user_is_signin')) {
    /**
     * 判断是否登录
     * @return mixed
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function user_is_signin()
    {
        $user = session('mall_user_auth');
        if (empty($user)) {
            return 0;
        } else {
            return session('mall_user_auth_sign') == data_auth_sign($user) ? $user['uid'] : 0;
        }
    }
}

if (!function_exists('user_role_auth')) {
    /**
     * 读取当前用户权限
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function user_role_auth()
    {
        session('user_role_menu_auth', model('user/role')->roleAuth());
    }
}

if (!function_exists('filter')) {
    /**
     * Notes:数据过滤转换
     * User: EricYan
     * @param $data
     * @param null $whiteList
     * @return array
     */
    function filter($data, $whiteList = null)
    {
        $newData = array();
        if (is_string($whiteList)) {
            $whiteList = explode(',', $whiteList);
        }
        foreach ($data as $item) {
            $newData[] = filter_data($item, $whiteList);
        }
        return $newData;
    }
}

if (!function_exists('filter_data')) {
    /**
     * Notes:数据过滤转换
     * User: EricYan
     * @param $data
     * @param null $whiteList
     * @return array
     */
    function filter_data($data, $whiteList = null)
    {
        $newData = array();
        if (is_string($whiteList)) {
            $whiteList = explode(',', $whiteList);
        }
        if (!$whiteList) {
            foreach ($data as $key => $item) {
                switch ($key) {
                    case 'cover_image':
                    case 'head_img':
                        $newData[$key] = get_file_url($data[$key]);
                        break;
                    default:
                        if ($data[$key] === null) {
                            $newData[$key] = '';
                        } else {
                            $newData[$key] = $data[$key];
                        }
                }
            }
        } else {
            foreach ($whiteList as $key) {
                switch ($key) {
                    case 'cover_image':
                    case 'head_img':
                        $newData[$key] = get_file_url($data[$key]);
                        break;
                    default:
                        if ($data[$key] === null) {
                            $newData[$key] = '';
                        } else {
                            $newData[$key] = $data[$key];
                        }
                }
            }
        }
        return $newData;
    }
}


if (!function_exists('time_tran')) {
    /**
     * 转换时间
     * @param int $timer 时间戳
     * @return string
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    function time_tran($timer)
    {
        $diff = $_SERVER['REQUEST_TIME'] - $timer;
        $day = floor($diff / 86400);
        $free = $diff % 86400;
        if ($day > 0) {
            return $day . " 天前";
        } else {
            if ($free > 0) {
                $hour = floor($free / 3600);
                $free = $free % 3600;
                if ($hour > 0) {
                    return $hour . " 小时前";
                } else {
                    if ($free > 0) {
                        $min = floor($free / 60);
                        $free = $free % 60;
                        if ($min > 0) {
                            return $min . " 分钟前";
                        } else {
                            if ($free > 0) {
                                return $free . " 秒前";
                            } else {
                                return '刚刚';
                            }
                        }
                    } else {
                        return '刚刚';
                    }
                }
            } else {
                return '刚刚';
            }
        }
    }
}
if (!function_exists('search_time')) {
    /**
     * @param $text
     * @param $length
     * @return string
     * author 吴秀芳
     * 2020/6/20 8:32
     * 处理时间搜索
     */
    function search_time($search_fields, $map, $model)
    {
        $wheretime = [];
        if (!empty($search_fields)) {
            foreach ($search_fields as $k => $v) {
                if ($v['type'] == 'datetime' || $v['type'] == 'between') {
                    $startname = $v['name'] . '_start';
                    $endname = $v['name'] . '_end';
                    $start = $map[$startname];
                    $end = $map[$endname];
                    $min = time_min($model, $v['name']);
                    $max = time_max($model, $v['name']);
                    if ($v['type'] == 'datetime') {
                        $start = strtotime($start);
                        $end = strtotime($end);
                    }
                    if ($start || $end) {
                        if (!$start) {
                            $start = $min;
                        }
                        if (!$end) {
                            $end = $max;
                        }
                        $time = [$v['name'], 'between', [$start, $end]];
                    }
                    unset($wheretime[$startname]);
                    unset($wheretime[$endname]);
                }

                if ($v['type'] == 'text') {
                    $time = [$v['prefix'] . $v['name'], 'like', '%' . $map[$v['name']] . '%'];
                }
                if ($v['type'] == 'select') {
                    if ($map[$v['name']]) {
                        if ($map[$v['name']] == 'all') {
//                                     $time = [$v['name'],'in','wxpay','alipay'];
                        } else {
                            if ($v['zero'] == 0) {
                                $maps = $map[$v['name']] - 1;
                                $time = [$v['name'], '=', $maps];
                            } else {
                                $time = [$v['name'], '=', $map[$v['name']]];
                            }
                        }
                    }
                }
                array_push($wheretime, $time);
            }
        }
        return $wheretime;
    }
}
if (!function_exists('time2string')) {
    /**
     * @param $second
     * @return string
     * author 吴秀芳
     * 2020/7/7 12:05
     * 计算剩余时间
     */
    function time2string($second)
    {
        $day = floor($second / (3600 * 24));
        $second = $second % (3600 * 24);//除去整天之后剩余的时间
        $hour = floor($second / 3600);
        $second = $second % 3600;//除去整小时之后剩余的时间
        $minute = floor($second / 60);
        $second = $second % 60;//除去整分钟之后剩余的时间
        //返回字符串
        if (empty($day)) {
            if (empty($hour)) {
                if (empty($minute)) {
                    $minute = 0;
                    $data = $minute . '天';
                } else {
                    $data = $minute . '分钟';
                }
            } else {
                $data = $hour . '小时';
            }
        } else {
            $data = $day . '天';
        }
        return $data;
//        return $day.'天'.$hour.'小时'.$minute.'分'.$second.'秒';
//        return $day.'天'.$hour.':'.$minute.':'.$second;
    }
}
if (!function_exists('check_password')) {
    /**
     * @param $second
     * @return string
     * author 吴秀芳
     * 2020/7/7 12:05
     * 检测密码
     */
    function check_password($password)
    {
        if (preg_match("/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,32}$/", $password)) {
            return true;
        } else {
            return false;
        }
    }
}
if (!function_exists('check_mobile')) {
    /**
     * @param $second
     * @return string
     * author 吴秀芳
     * 2020/7/7 12:05
     * 检测密码
     */
    function check_mobile($mobile)
    {
        if (!preg_match("/^1\d{10}$/", $mobile)) {
            return false;
        } else {
            return true;
        }
    }
}
if (!function_exists("push")) {
    /**
     * @param $nickname
     * author 吴秀芳
     * 2020/7/9 18:13
     * 极光推送
     */
    function push($accept_id, $message)
    {
        $data = addons_action('Jiguang', 'JPush', 'getClient', 'push');
        $id = Db::name('user_info')->where(['user_id' => $accept_id])->value('register_id');
        $result = $data->setPlatform('all')
            //        ->addAllAudience()
            ->addRegistrationId($id)
            ->setNotificationAlert($message)
            ->send();
        if ($result['http_code'] = 200) {
            return true;
        } else {
            return false;
        }
    }
}
if (!function_exists("getTimeConversion")) {
    /**
     * 获取时间周期统一方法
     * @param $time 所取时间阶段标识(参数请参考方法参数值)
     * @param $timeFormat 返回时间区间的格式(ymd:年月日格式;stamp:时间戳格式)
     * @return array
     * @since 2020年11月2日16:00:21
     * @author zenghu < 1427305236@qq.com >
     */
    function getTimeConversion($time = 'day', $timeFormat = 'ymd')
    {
        // 定义返回的时间
        $returnTime = [];

        // 获取指定时间段节点
        switch ($time) {
            case 'day': // 当天
            case 'd':
                $returnTime['startTime'] = date('Y-m-d') . ' 00:00:00';
                $returnTime['endTime'] = date('Y-m-d') . ' 23:59:59';
                break;

            case 'yesterday': // 昨天
            case 'ystd':
                $returnTime['startTime'] = date("Y-m-d", strtotime("-1 day")) . ' 00:00:00';
                $returnTime['endTime'] = date("Y-m-d", strtotime("-1 day")) . ' 23:59:59';
                break;

            case 'tomorrow': // 明天
            case 'tmr':
                $returnTime['startTime'] = date("Y-m-d", strtotime("+1 day")) . ' 00:00:00';
                $returnTime['endTime'] = date("Y-m-d", strtotime("+1 day")) . ' 23:59:59';
                break;

            case 'week': // 本周
            case 'w':
                $timeStr = date('w') == 1 ? 'Monday' : 'last Monday';
                $returnTime['startTime'] = date("Y-m-d", strtotime("$timeStr")) . ' 00:00:00';
                $returnTime['endTime'] = date("Y-m-d", strtotime("Sunday")) . ' 23:59:59';
                break;

            case 'lastweek': // 上周
            case 'lw':
                $timeStr = date('w') == 1 ? 'last Monday' : 'last Monday -7 days';
                $returnTime['startTime'] = date("Y-m-d", strtotime("$timeStr")) . ' 00:00:00';
                $returnTime['endTime'] = date("Y-m-d", strtotime("last Sunday")) . ' 23:59:59';
                break;

            case 'nextweek': // 下周
            case 'nw':
                $timeStr = date('w') == 2 ? 'Monday 7 days' : 'Monday';
                $returnTime['startTime'] = date("Y-m-d", strtotime("$timeStr")) . ' 00:00:00';
                $returnTime['endTime'] = date("Y-m-d", strtotime("Sunday 7 days")) . ' 23:59:59';
                break;

            case 'halfmonth': // 半个月
            case 'hm':
                $timeStr = date('w') == 1 ? 'last Monday' : 'last Monday -7 days';
                $returnTime['startTime'] = date("Y-m-d", strtotime("$timeStr")) . ' 00:00:00';
                $returnTime['endTime'] = date("Y-m-d", strtotime("Sunday")) . ' 23:59:59';
                break;

            case 'month': // 本月
            case 'm':
                $returnTime['startTime'] = date("Y-m-01") . ' 00:00:00';
                $returnTime['endTime'] = date('Y-m-t') . ' 23:59:59';
                break;

            case 'lastmonth': // 上个月
            case 'lm':
                $returnTime['startTime'] = date("Y-m-01", strtotime("last month")) . ' 00:00:00';
                $returnTime['endTime'] = date('Y-m-t', strtotime("last month")) . ' 23:59:59';
                break;

            case 'nextmonth': // 下个月
            case 'nm':
                $returnTime['startTime'] = date("Y-m-01", strtotime("next month")) . ' 00:00:00';
                $returnTime['endTime'] = date('Y-m-t', strtotime("next month")) . ' 23:59:59';
                break;

            case 'lastquarter': // 上季度
            case 'lq':
                $season = ceil((date('n')) / 3); // 当月是第几季度
                if ($season == 1) {
                    $returnTime['startTime'] = date("Y-10-01", strtotime("last year")) . ' 00:00:00';
                    $returnTime['endTime'] = date("Y-12-31", strtotime("last year")) . ' 23:59:59';
                } else {
                    $season = $season - 1;
                    $returnTime['startTime'] = date("Y-" . sprintf("%02d", ($season * 3 - 2)) . "-01") . ' 00:00:00';
                    $returnTime['endTime'] = date("Y-" . sprintf("%02d", $season * 3) . "-t") . ' 23:59:59';
                }
                break;

            case 'nextquarter': // 下季度
            case 'nq':
                $season = ceil((date('n')) / 3); // 当月是第几季度
                if ($season == 4) {
                    $returnTime['startTime'] = date("Y-01-01", strtotime("next year")) . ' 00:00:00';
                    $returnTime['endTime'] = date("Y-03-31", strtotime("next year")) . ' 23:59:59';
                } else {
                    $season = $season + 1;
                    $returnTime['startTime'] = date("Y-" . sprintf("%02d", ($season * 3 - 2)) . "-01") . ' 00:00:00';
                    $returnTime['endTime'] = date("Y-" . sprintf("%02d", $season * 3) . "-t") . ' 23:59:59';
                }
                break;

            case 'quarter': // 本季度
            case 'q':
                $season = ceil((date('n')) / 3); // 当月是第几季度
                $returnTime['startTime'] = date("Y-" . sprintf("%02d", ($season * 3 - 2)) . "-01") . ' 00:00:00';
                $returnTime['endTime'] = date("Y-" . sprintf("%02d", $season * 3) . "-t") . ' 23:59:59';
                break;

            case 'year': // 本年
            case 'y':
                $returnTime['startTime'] = date("Y-01-01") . ' 00:00:00';
                $returnTime['endTime'] = date('Y-12-31') . ' 23:59:59';
                break;

            case 'lastyear': // 前年
            case 'ly':
                $returnTime['startTime'] = date("Y-01-01", strtotime("last year")) . ' 00:00:00';
                $returnTime['endTime'] = date('Y-12-31', strtotime("last year")) . ' 23:59:59';
                break;

            case 'lastyear2': // 前两年
            case 'ly2':
                $returnTime['startTime'] = date("Y-01-01", strtotime("-2 year")) . ' 00:00:00';
                $returnTime['endTime'] = date("Y-12-31", strtotime("-2 day")) . ' 23:59:59';
                break;

            case 'lastyear3': // 前三年
            case 'ly3':
                $returnTime['startTime'] = date("Y-01-01", strtotime("-3 year")) . ' 00:00:00';
                $returnTime['endTime'] = date("Y-12-31", strtotime("-3 day")) . ' 23:59:59';
                break;

            case 'nextyear': // 下年
            case 'ny':
                $returnTime['startTime'] = date("Y-01-01", strtotime("next year")) . ' 00:00:00';
                $returnTime['endTime'] = date('Y-12-31', strtotime("next year")) . ' 23:59:59';
                break;

            default:
                $returnTime['startTime'] = '';
                $returnTime['endTime'] = '';
                break;
        }

        // 根据需要的时间格式返回对应的时间数据
        if ($timeFormat == 'stamp') {
            $returnTime['startTime'] = strtotime($returnTime['startTime']);
            $returnTime['endTime'] = strtotime($returnTime['endTime']);
        }

        return $returnTime;
    }
}

if (!function_exists("returnData")) {
    /**
     * 统一返回
     * @param $status 返回状态
     * @param $result 返回的数据结果
     * 2000 : 成功 ， 5000 ： 失败 ，
     */
    function returnData($status = '2000', $msg = '成功', $result = array())
    {
        $str = ['status' => $status, 'msg' => $msg, 'result' => $result];
        return json_encode(unserialize(str_replace(array('NAN;', 'INF;'), '0;', serialize($str))));
        // return json_encode(['status'=>$status, 'msg'=>$msg, 'result'=>$result]);
    }
}
if (!function_exists("format_data")) {
    /**
     * 格式化返回数据
     * @param $code 1成功 0失败
     * @param $data 返回的数据
     * @param $msg 返回的信息
     * @time 2021年4月23日09:10:04
     * @author chenchen
     */
    function format_data($code = 0, $data = [], $msg = '')
    {
        $res = [
            'code' => $code,
            'data' => $data,
            'msg' => $msg
        ];
        return $res;

    }
}
if (!function_exists("default_lang")) {
    /**
     * 系统默认语言
     * @author chenchen
     * @time 2021年4月27日10:17:38
     */
    function default_lang()
    {
        $lang = 'zh-cn';
        $lang_arr = lang_array();
        $http_accept_language = $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? $lang;
        // 读取浏览器语言标识
        preg_match('/^([a-z\-]+)/i', $http_accept_language, $matches);
        if (isset($matches[1])) {
            $matches_small = strtolower($matches[1]);
            if ($matches_small == 'zh-hk' || $matches_small == 'zh-mo') {
                $matches_small = 'zh-tw';
            }
            if (in_array($matches_small, $lang_arr)) {
                $lang = $matches_small;
            }
        }
        //语言切换
        $language = $_COOKIE['language'] ?? '';
        if (in_array(strtolower($language), $lang_arr)) {
            $lang = strtolower($language);
        }
        return $lang;
    }
}

if (!function_exists("lang_array")) {
    /**
     * 支持的语言数组
     * @author chenchen
     * @time 2021-4-27 14:26:30
     */
    function lang_array()
    {
        return [
            '简' => 'zh-cn',
            '繁' => 'zh-tw',
            'English' => 'en-us',
            '日本語' => 'ja-jp',
            '한국어' => 'ko-kr',
            'русский' => 'ru-ru',
            'Español' => 'es-es',
            'Ελληνικά' => 'el-el',
            'Deutsch' => 'de-de',
            'Français' => 'fr-fr',
        ];
    }
}

if (!function_exists("is_timestamp")) {
    /**
     * 是否是时间戳
     * @author chenchen
     * @time 2021年5月27日18:48:58
     */
    function is_timestamp($timestamp)
    {
        if (strtotime(date('m-d-Y H:i:s', $timestamp)) === $timestamp) {
            return $timestamp;
        } else {
            return false;
        }
    }
}
if (!function_exists("check_money")) {
    /**
     * 检测下单金额是否一致
     * @param $payable_money float 下单时计算出的订单实际支付金额
     * @param $money float 下单时传过来的订单实际支付金额
     * @time 2021年6月5日09:19:41
     * @author chenchen
     */
    function check_money($money, $payable_money)
    {
        $delta = 0.001;
        if (abs($money - $payable_money) < $delta) {
            return true;
        } else {
            return false;
        }
    }
}

if (!function_exists("myaddslashes")) {
    //转义mysql语句中的字符
    function myaddslashes($data)
    {
        if (false == get_magic_quotes_gpc()) {
            //未启用魔术引用时,转义特殊字符
            return addslashes($data);
        }
        return $data;
    }
}

if (!function_exists("filter_sql")) {
    //过滤常见的sql注入特殊字符
    function filter_sql($param)
    {
        $filter = ["select", 'insert', "update", "delete", "'", "/*", 'or',
            "../", "./", "union", "into", "load_file",
            "outfile", "=", "aNd", "!", "script>", "<", ">", "iframe>", 'onload', '">'
        ];
        return str_ireplace($filter, '', $param);
    }
}

if (!function_exists("get_file_local_path")) {
    //获取上传文件的本地路径uploads开头
    function get_file_local_path($file)
    {
        $file = str_ireplace('\\', '/', $file);
        $file = substr($file, strpos($file, '/uploads') + 1);
        return $file;
    }
}
if (!function_exists("arr_foreach")) {
    //数组降维
    function arr_foreach($array, $return = [])
    {
        array_walk_recursive($array, function ($value) use (&$return) {
            $return[] = $value;
        });
        return $return;
    }
}

if (!function_exists("uncamelize")) {

    /**
     * 驼峰命名转下划线命名
     */
    function uncamelize($camelCaps, $separator = '_')
    {
        return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
    }
}
if (!function_exists('get_img_rgb')) {
    /**
     * 获取图片rgb
     * @param $img
     * @return int[]
     */
    function get_img_rgb($img)
    {
        $rTotal = 0;
        $gTotal = 0;
        $bTotal = 0;
        $total = 0;
        $i = imagecreatefrompng($img);
        if (!$i) {
            $i = imagecreatefromjpeg($img);
        }
        for ($x = 0; $x < imagesx($i); $x++) {
            for ($y = 0; $y < imagesy($i); $y++) {
                $rgb = imagecolorat($i, $x, $y);
                $r = ($rgb >> 16) & 0xFF;
                $g = ($rgb >> 8) & 0xFF;
                $b = $rgb & 0xFF;
                $rTotal += $r;
                $gTotal += $g;
                $bTotal += $b;
                $total++;
            }
        }
        if ($total == 0) {
            $rAverage = 0;
            $gAverage = 0;
            $bAverage = 0;
        } else {
            $rAverage = round($rTotal / $total);
            $gAverage = round($gTotal / $total);
            $bAverage = round($bTotal / $total);
        }

        return [$rAverage, $gAverage, $bAverage];
    }
}
if (!function_exists("post_json_data")) {
    /**
     * Notes: curl 发送post请求
     * User: chenchen
     * Date: 2021/7/3
     * Time: 14:31
     * @param $url string 请求地址
     * @param $data_string string 请求数据
     * @return array
     */
    function post_json_data($url, $data_string)
    {
        //初始化
        $ch = curl_init();
        //设置post方式提交
        curl_setopt($ch, CURLOPT_POST, 1);
        //设置抓取的url
        curl_setopt($ch, CURLOPT_URL, $url);
        //设置post数据
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        //设置头文件的信息作为数据流输出
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($data_string))
        );
        ob_start();
        //执行命令
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return array('code' => $return_code, 'result' => $return_content);
    }
}

//公共的返回方法
function frontReturn($code, $msg, $data = [])
{
    return \service\ApiReturn::r($code, $data, $msg);
}

//统一获取用户信息方法
function getUserInfo($userId)
{
    $user = \app\user\model\User::alias('u')
        ->join('user_info i', 'i.user_id=u.id')
        ->field('u.*')
        ->field('i.*')
        ->where('id', $userId)
        ->find();
    if (empty($user)) {
        return [];
    }
    return $user;
}
